<template>
  <el-form 
      ref="formobj"
      :model="lyform" 
      :rules="rules"
      label-width="100px">
      <el-form-item label="编号" prop="code">
          <el-input v-model="lyform.code" maxlength="64" placeholder="请输入科室编号"></el-input>
      </el-form-item>
      <el-form-item label="科室名称" prop="name">
          <el-input v-model="lyform.name" maxlength="64" placeholder="请输入科室名称"></el-input>
      </el-form-item>
      <el-form-item label="科室类别" prop="type">
          <el-input v-model="lyform.type" maxlength="64" placeholder="请输入科室类别"></el-input>
      </el-form-item>
      <el-form-item >
          <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { post, get } from '@/utils/axios';
import { ElMessage } from 'element-plus';
import { url } from './api'
const props = defineProps(['id'])
if(props.id){
  getById()
}
const lyform = reactive({
  code: '',
  name: '',
  type: ''
})
const emits = defineEmits(['update:show', 'getTableData'])
const rules = reactive({
  code: [
    { required: true, message: '请输入科室编码', trigger: 'blur' },
    { validator: (rule, value, callback) => { check(rule, value, callback, 'code') }, message: '该科室编码已经存在', trigger: 'blur'  }
  ],
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { validator: (rule, value, callback) => { check(rule, value, callback, 'name') }, message: '该科室名称已经存在', trigger: 'blur'  }
  ],
  type: [
    { required: true, message: '请输入科室类别', trigger: 'blur' }
  ]
})
const formobj = ref()
function getById(){
  get(url.getById, { id: props.id }, content => {
    for(let key in lyform){   /// 使用循环赋值
      if(Object.prototype.hasOwnProperty.call(content, key)){// 判断是否是自身属性
        lyform[key] = content[key]
      }
    }
    lyform.id = props.id
  })
}
function save () {
  post(props.id ? url.update : url.add, lyform, content => { //异步操作
    emits('update:show', false)
    emits('getTableData')
  }, formobj)
}
function check (rule, value, callback, field) {
  get(url.check, { field, value, id: props.id }, content => {
    if (content) {
      callback()
    } else {
      callback(new Error())
    }
  })
}
</script>

<style lang="scss" scoped>
</style>